<script>

import MapDialog from "./components/MapDialog.vue";
import SaveDialog from "./components/SaveDialog.vue";
import KtMap from "/src/components/common/KtMap.vue";
import SensorDialog from "./components/SensorDialog.vue";
import iot from "/src/js/iot/index.js";


export default {
  components: {KtMap, SaveDialog, MapDialog, SensorDialog},
  data() {
    return {
      iot,
      mapLoaded: true,
      bodyData: [],
      requestParamBind: {
        name: "",
        projectId: ""
      },
      contentLoading: false,
      type: "card",
      mapBodyData: {
        center: {
          longitude: 103.8198,
          latitude: 1.3521
        },
        markers: [
          {
            latitude: 1.3521,
            longitude: 103.8198,
            title: "新加坡"
          }
        ]
      },
      requestParam:{
        data:{
          deviceId: "",
          projectId: "",
          gmtStartTime: "",
          gmtEndTime: ""
        },
        pageSize:1,
        pageNumber: 100
      },
      projectList: [],
      deviceList:
          [{
            "gmtCreate": 1727525700975,
            "gmtModified": 1728479240478,
            "id": 10,
            "interval": 1,
            "latitude": 2.17,
            "longitude": 103.32,
            "name": "设备1",
            "online": {"deviceId": 10, "gmtLastHeartbeat": null, "isOnline": false},
            "priority": 11111,
            "projectId": 6,
            "protocolCode": "modbusRTU",
            "sn": "02100824090900030075",
            "uploadCycle": null
          }]

    }
  },
  async created() {
    await this.getProjectList();
    this.getBodyData();
  },
  mounted() {

  },
  methods: {
    // 获取项目列表
    getProjectList() {
      return new Promise((resolve, reject) => {
        this.$kt.request.send({
          uri: "/business-iot-web/admin/iotProject/getAll",
          data: {},
          stateSuccess: (res) => {
            this.projectList = res.data;
            // 默认选择第一个
            if (this.projectList.length > 0) {
              // this.requestParamBind.projectId = this.projectList[0].id;
              this.selectProject(this.projectList[0]);
            }
            resolve();
          },
          stateFail: (err) => {
            this.$message.error(err.errMsg);
            reject();
          }
        });
      });
    },
    // 获取设备列表
    getDeviceList() {
      return new Promise((resolve, reject) => {
        this.$kt.request.send({
          uri: "/business-iot-web/admin/iotDevice/getAll",
          data: {
            and: [{
              field: "projectId",
              value: this.requestParamBind.projectId,
              operatorCode: "eq"
            }]
          },
          stateSuccess: (res) => {
            this.deviceList = res.data;
            resolve();
          },
          stateFail: (err) => {
            this.$message.error(err.errMsg);
            reject();
          }
        });
      });
    },

    toRemove(item) {
      // 是否确定删除,
      this.$confirm(this.$i18n.zhToGlobal('是否确定删除？'), this.$i18n.zhToGlobal('提示'), {
        confirmButtonText: this.$i18n.zhToGlobal('确定'),
        cancelButtonText: this.$i18n.zhToGlobal('取消'),
        type: 'warning',
      }).then(() => {
        this.contentLoading = true;
        this.$kt.request.send({
          uri: "/business-iot-web/admin/iotDevice/remove",
          data: {
            id: item.id
          },
          stateSuccess: (res) => {
            this.getBodyData();
            this.contentLoading = false;
          },
          stateFail: (err) => {
            this.$message.error(err.errMsg);
            this.contentLoading = false;
          }
        });
      }).catch(() => {
      });
    },
    toMap(item) {
      this.$refs.mapDialog.open(item.title, {
        center: {
          longitude: item.longitude,
          latitude: item.latitude
        },
        markers: [
          {
            latitude: item.latitude,
            longitude: item.longitude,
            title: ""
          }
        ]
      });
    },
    getBodyData() {
      this.contentLoading = true;
      this.$kt.request.send({
        uri: "/business-iot-web/admin/iotDeviceHistory/getBodyDataNew",
        data: this.requestParam,
        stateSuccess: (res) => {
          this.contentLoading = false;
          this.bodyData = res.data;
        },
        stateFail: (err) => {
          this.$message.error(err.errMsg);
          this.contentLoading = false;
        }
      });
    },
    selectProject(item) {
      this.requestParamBind.projectId = item.id;
      this.getDeviceList();
      // this.getAll();
    },
    /**
     * 判断是否在线
     */
    isOnline(item) {
      // 判断最后一次心跳时间是否超过设置的间隔
      if (item.online?.gmtLastHeartbeat) {
        const gmtLastHeartbeat = new Date(item.online?.gmtLastHeartbeat).getTime();
        const now = new Date().getTime();
        const interval = item.interval * 1000;
        if (now - gmtLastHeartbeat < interval) {
          return true;
        }
      }
      return false;
    }
  }
}
</script>

<template>
  <div>

    <map-dialog
        ref="mapDialog"
    ></map-dialog>

    <save-dialog
        @save="getBodyData"
        ref="saveDialog"></save-dialog>
    <div style="display: inline-block;width: 180px;height: 100vh">
      <div style="font-weight: bold;font-size: 16px;text-align: center">{{ $i18n.zhToGlobal("项目列表") }}</div>
      <div style="height: 10px"></div>
      <el-scrollbar style="height: calc(100vh - 60px)">
        <div
            style="padding: 10px;box-sizing: border-box"
            v-for="item in projectList">
          <div class="card-project"
               :class="{
            'card-project-selected': requestParamBind.projectId === item.id
          }"
               @click="selectProject(item)"
          >
            {{ item.title }}
          </div>
        </div>
      </el-scrollbar>
    </div>

    <div
        style="position: relative;display: inline-block;width: calc(100vw - 200px);margin-left: 10px;height: 100vh;vertical-align: top;">

      <div
          style="position: relative">

        <el-form
            @submit.native.prevent
        >
          <el-row gutter="10">
            <el-col :span="6">
              <el-form-item :label="$i18n.zhToGlobal('设备')">
                <el-select v-model="requestParamBind.deviceId" clearable>
                  <el-option
                      v-for="item in deviceList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- 开始时间 -->
              <el-form-item :label="$i18n.zhToGlobal('开始时间')">
                <el-date-picker
                    v-model="requestParamBind.startTime"
                    type="datetime"
                    placeholder="选择日期时间"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- 结束时间 -->
              <el-form-item :label="$i18n.zhToGlobal('结束时间')">
                <el-date-picker
                    v-model="requestParamBind.endTime"
                    type="datetime"
                    placeholder="选择日期时间"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <div style="position: absolute;right: 0;top: 0">
          <!-- 刷新 -->
          <el-button
              type="primary"
              @click="getBodyData">
            <kt-icon
                class="el-icon-refresh"
                color="#fff"
                @click="getBodyData"
                icon="el-icon-refresh">
            </kt-icon>
          </el-button>

          <el-button
              type="primary"
              @click="$refs.saveDialog.openNew(requestParamBind.projectId)">
            <kt-icon
                class="icon-add"
                color="#fff"
                icon="el-icon-plus">
            </kt-icon>
          </el-button>
        </div>
      </div>



        <!-- 更改头部颜色 -->
        <el-table
            :data="bodyData.content"
            style="width: 100%"
            border
            height="calc(100vh - 120px)">

          <el-table-column
              prop="id"
              :label="$i18n.zhToGlobal('ID')"
              width="200">
          </el-table-column>

          <el-table-column
              prop="sensor.name"
              :label="$i18n.zhToGlobal('传感器')"
              width="200">
          </el-table-column>

          <el-table-column
              prop="sensorValue"
              :label="$i18n.zhToGlobal('值')"
              width="200">
          </el-table-column>

          <el-table-column
              prop="sensorUnit"
              :label="$i18n.zhToGlobal('传感器单位')"
              width="200">
            <template slot-scope="scope">
              {{ iot.getUnitLabel(scope.row.sensorUnit) }}
            </template>
          </el-table-column>

          <el-table-column
              :label="$i18n.zhToGlobal('时间')"
              width="200">
          </el-table-column>



        </el-table>

      <div class="bottom">

        <!--   分页 -->
        <el-pagination
            background
            layout="prev, pager, next"
            :page-size="requestParam.pageSize"
            :total="bodyData.totalElements"
            :current-page="requestParam.pageNumber"
            @current-change="getBodyData"
            @size-change="getBodyData"
        >
        </el-pagination>

      </div>



    </div>


    <sensor-dialog
        ref="sensorDialog"></sensor-dialog>

  </div>
</template>

<style scoped lang="scss">

.card {
  position: relative;
  margin: 10px;
  border: 1px solid #e8e8e8;
  border-radius: 5px;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
  background-color: #fff;
  width: 300px;
  display: inline-block;

  .card-header {
    padding: 10px;
    border-bottom: 1px solid #e8e8e8;

    .card-title {
      font-size: 16px;
      font-weight: bold;

      .card-sn {
        font-size: 12px;
        font-weight: lighter;
        margin-left: 10px;
        float: right;
      }
    }

  }

  .card-body {
    padding: 10px;

    .card-text {
      font-size: 14px;
    }
  }
}

.scrollbar {
  height: 100px;
  overflow: auto;
  padding: 10px;

  .el-scrollbar__wrap {
    padding: 0;
  }

  .el-scrollbar__view {
    padding: 0;
  }

  .el-scrollbar__bar {
    background-color: #e8e8e8;
  }

  .el-scrollbar__thumb {
    background-color: #999;
  }
}

.card-lon-lat {
  font-size: 12px;
  font-weight: lighter;
  padding: 10px;
  cursor: pointer;
}

.card-lon-lat:hover {
  opacity: .6;
}

.card-lon-lat:active {
  opacity: 1;
}

.icon-edit {
  cursor: pointer;
}

.icon-delete {
  cursor: pointer;
}

.icon-btn:hover {
  transform: scale(1.1);
}

.icon-btn:active {
  transform: scale(1);
}

.scrollbar-box {
  height: calc(100vh - 120px);
  padding: 10px;
  text-align: center;
}


.map-box {
  width: 100%;
  height: calc(100vh - 120px);
  border-radius: 5px;
  overflow: hidden;
}

.card-project {
  padding: 10px;
  cursor: pointer;
  background-color: #f8f8f8;
  border-radius: 20px;
  text-align: center;
}

.card-project-selected {
  background-color: #333;
  color: #fff;
}


.bottom{
  position: fixed;
  bottom: 20px;
  width: 100%;
  text-align: center;
  margin-top: 20px;
  // 超出不显示
  overflow: hidden;
}
</style>